import { getToken, setToken, removeToken } from '@/utils/auth'
import Admin from '@/api/admin.js'
import { useaddRoute, getAsyncRoute } from '@/utils/asyncRouter'
const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: '',
    power: 0
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_POWER: (state, power) => {
      state.power = power
    }

  },

  actions: {
    // 登录
    Login ({ commit }, userinfo) {
      return new Promise((resolve, reject) => {
        Admin.Adminlogin(userinfo).then(response => {
          const token = response.data.token
          setToken(token)
          commit('SET_TOKEN', token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 重置密码登录
    unsetLogin ({ commit }, userinfo) {
      return new Promise((resolve, reject) => {
        Admin.unsetPasswordLogin(userinfo).then(response => {
          const token = response.data.token
          setToken(token)
          commit('SET_TOKEN', token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo ({ commit, state }) {
      return new Promise((resolve, reject) => {
        Admin.getInfo(state.token).then(response => {
          const data = response.data
          if (data.roles === 2 || data.roles === 1 || data.roles === 0) {
            commit('SET_ROLES', data.roles)
            useaddRoute(data.roles, data.state)
          } else {
            reject('权限错误，请联系管理员')
          }
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.unset)
          commit('SET_POWER', data.state)
          const list = getAsyncRoute(data.roles, data.state)
          resolve(list)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut ({ commit, state }) {
      return new Promise((resolve, reject) => {
        Admin.AdminLogout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_POWER', '')
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut ({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_POWER', '')
        removeToken()
        resolve()
      })
    },
    getRouter ({ commit, state }) {
      return new Promise(resolve => { resolve(getAsyncRoute(state.roles, state.power)) })
    }
  }
}

export default user
